#include "Socket.hpp"
#include "Protocol.hpp"
#include <time.h>
#include <assert.h>

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}


int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    Sock sock;
    sock.Socket();
    bool r = sock.Connect(serverip, serverport);
    if(!r) return -1;

    srand((unsigned int)time(nullptr) ^ getpid());
    int cnt = 1;
    const char* oper = "+-*/%=^&";


    std::string inbuffer_stream;
    while(cnt <= 20)
    {
        std::cout << "===============第" << cnt << "次测试....., " << "===============" << std::endl;
        int x = rand() % 100;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char op = oper[rand() % sizeof(oper)];

        Request req(x,y,op);
        req.DebugPrint();
        std::string package;
        req.Serialize(&package);
        package = Encode(package);

        int n = write(sock.Fd(), package.c_str(), package.size());
        // std::cout << "这是最新的发出去的请求: " << n << "\n" << package;
        // n = write(sock.Fd(), package.c_str(), package.size());
        // std::cout << "这是最新的发出去的请求: \n" << n << "\n" << package;
        // n = write(sock.Fd(), package.c_str(), package.size());
        // std::cout << "这是最新的发出去的请求: \n" << n << "\n" << package;
        // n = write(sock.Fd(), package.c_str(), package.size());
        // std::cout << "这是最新的发出去的请求: \n" << n << "\n" << package;
        
        char buffer[128];
        n = read(sock.Fd(), buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;
            std::cout << inbuffer_stream << std::endl;

            std::string content;
            bool r = Decode(inbuffer_stream, &content);
            assert(r);

            Response rsp;
            r = rsp.Deserialize(content);
            assert(r);
            rsp.DebugPrint();
        }
        else
        {
            break;
        }

        std::cout << "=======================================" << std::endl;
        sleep(1);
        cnt++;
    }

    sock.Close();
    
    return 0;
}